<?php
/**
 * 翼支付接口//zmr>v30
 *
 *
 */
defined('InShopNC') or exit('Access Invalid!');
require_once("phpseclib1.0.1/Math/BigInteger.php");
require_once("phpseclib1.0.1/Crypt/Base.php");
require_once("phpseclib1.0.1/Crypt/Hash.php");
require_once("phpseclib1.0.1/Crypt/Rijndael.php");
require_once("phpseclib1.0.1/Crypt/AES.php");
require_once("phpseclib1.0.1/Crypt/RSA.php");
class bestpay {
    
    
    function generate_pay_button($order, $payment) {
        $MerchantPwd = $payment['BESTPAY_PWD'];
        $URL = "https://capi.bestpay.com.cn";
        
        //step 1: generate order
        $orderseq = $order['order_sn'];
        $orderdate = date('Ymd');
        $ordereqtranseq = $order['order_sn'].date('YmdHis').mt_rand(10000,99999);
        $subject=$order['order_type']=='r'?"实物订单".$orderseq:"虚拟订单".$orderseq;
        $order_amount= (int)(((float)$order['order_amount'])*100);
        	
        $time=date('YmdHis');
        	
        $mac = 'MERCHANTID='.$payment['MERCHANTID'].'&ORDERSEQ='.$orderseq.'&ORDERREQTRANSEQ='.$ordereqtranseq.'&ORDERREQTIME='.$time.'&KEY='.$payment['KEY'];
        	
        $mac = strtoupper(md5($mac));
        
        $order_params=array(
            'MERCHANTID' => $payment['MERCHANTID'],
            'ORDERSEQ'=>$orderseq,
            'ORDERREQTRANSEQ'=>$ordereqtranseq,
            'ORDERREQTIME'=>"$time",
            'TRANSCODE'=>'01',
            'ORDERAMT'=>"$order_amount",
            'ORDERCCY'=>'RMB',
            'SERVICECODE'=>'05',
            'PRODUCTID'=>'04',
            'PRODUCTDESC'=>$subject,
            'REQUESTSYSTEM'=>'1',
            'ENCODETYPE'=>'1',
            'MAC'=>$mac
        );
        
        $paramsJoined = array();
        foreach($order_params as $param => $value) {
            $paramsJoined[] = "$param=$value";
        }
        $paramData = implode('&', $paramsJoined);
        	
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL                =>  "https://webpaywg.bestpay.com.cn/order.action",
            CURLOPT_POST               =>  1,
            CURLOPT_SSL_VERIFYPEER     =>  FALSE,
            CURLOPT_SSL_VERIFYHOST     =>  FALSE,
            CURLOPT_RETURNTRANSFER     =>  1,
            CURLOPT_POSTFIELDS         =>  $paramData
        ));
        
        $data = curl_exec($ch);
        curl_close($ch);
        	
        $button="<div></div>";
        if($data!="00&手机客户端下单成功")
        {
            return $data;
        
        }
        
        //step 2 fetch the pubkey
        $params=array(
            'keyIndex' => '',
            'encryKey' => '',
            'encryStr' => '',
            'interCode' => 'INTER.SYSTEM.001'
        );
        	
        $paramData=json_encode($params);
        	
        	
        $ch = curl_init();
        $header =  array('Content-Type: application/json');
        curl_setopt_array($ch, array(
            CURLOPT_URL                =>  $URL."/common/interface",
            CURLOPT_HTTPHEADER         =>  $header,
            CURLOPT_POST               =>  1,
            CURLOPT_SSL_VERIFYPEER     =>  FALSE,
            CURLOPT_SSL_VERIFYHOST     =>  FALSE,
            CURLOPT_RETURNTRANSFER     =>  1,
            CURLOPT_POSTFIELDS         =>  $paramData
        ));
        	
        $data = curl_exec($ch);
        curl_close($ch);
        
        $res_arr = json_decode($data,true);
        if($res_arr && $res_arr['success'])
        {
            //get the params
            $keyIndex=$res_arr['result']['keyIndex'];
            $pubKey=$res_arr['result']['pubKey'];
        
            $pay_params=array(
                'SERVICE' => 'mobile.securitypay.pay',
                'MERCHANTID' => $payment['MERCHANTID'],
                'MERCHANTPWD' => $MerchantPwd,
                'BEFOREMERCHANTURL' => $payment['BACKURL'],
                'BACKMERCHANTURL' => $payment['BACKURL'],
                'ORDERSEQ'=>$orderseq,
                'ORDERREQTRANSEQ'=>$ordereqtranseq,
                'ORDERTIME'=>"$time",
                'CURTYPE'=>'RMB',
                'ORDERAMOUNT'=>$order['order_amount'],
                'SUBJECT'=>$subject,
                'PRODUCTID'=>'04',
                'SIGNTYPE'=>'MD5',
                'PRODUCTDESC'=>$subject,
                'PRODUCTAMOUNT'=>$order['order_amount'],
                'ATTACHAMOUNT'=>'0',
                'CUSTOMERID'=>'1',
                'BUSITYPE'=>'04',
                'SWTICHACC'=>'false'
            );
        
        
            $paramsJoined = array();
            foreach($pay_params as $param => $value) {
                $paramsJoined[] = "$param=$value";
            }
            $pay_paramData = implode('&', $paramsJoined);
        
            $sign_params=array(
                'SERVICE' => 'mobile.securitypay.pay',
                'MERCHANTID' => $payment['MERCHANTID'],
                'MERCHANTPWD' => $MerchantPwd,
                'SUBMERCHANTID' => '',
                'BACKMERCHANTURL'=>$payment['BACKURL'],
                'ORDERSEQ'=>$orderseq,
                'ORDERREQTRANSEQ'=>$ordereqtranseq,
                'ORDERTIME'=>"$time",
                'ORDERVALIDITYTIME'=>'',
                'CURTYPE'=>'RMB',
                'ORDERAMOUNT'=>$order['order_amount'],
                'SUBJECT'=>$subject,
                'PRODUCTID'=>'04',
                'PRODUCTDESC'=>$subject,
                'CUSTOMERID'=>'1',
                'SWTICHACC'=>'false',
                'KEY'=>$payment['KEY']
            );
        
            $paramsJoined = array();
            foreach($sign_params as $param => $value) {
                $paramsJoined[] = "$param=$value";
            }
            $sign_paramData = implode('&', $paramsJoined);
        
            $sign = strtoupper(md5($sign_paramData));
        
            $pay_paramData.="&SIGN=".$sign;
        
        
            $random_key=md5(mt_rand());
            $cipher = new Crypt_AES();
            $cipher->setKey($random_key);
            $crypttext = base64_encode($cipher->encrypt($pay_paramData));
        
            $rsa = new Crypt_RSA();
            $rsa->loadKey($pubKey);
        
            $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
            $encrypted = base64_encode($rsa->encrypt($random_key));
        
        
            $webUrl = $URL."/gateway.pay?platform=wap_3.0&encryStr=".$crypttext."&keyIndex=".$keyIndex."&encryKey=".$encrypted;
            $webUrl = str_replace("+","%2B",$webUrl);
        
            $button = '<body onload="javascript:window.location.href=\''.$webUrl.'\'"><center>正在跳转支付页面...</center></body>';
        
        }
        	
        return $button;
    }
    
    /**
     * 获取return信息
     */
    public function getReturnInfo($payment_config) {
        $resultCode = $_GET['resultCode'];
        
        if($resultCode == -1) {
            return array(
                'resultCode' => $_GET['resultCode'],
                'result' => $_GET['result'],
                'orderSeq' => $_GET['orderSeq'],
                'orderAmt' => $_GET['orderAmt']
            );
        }
    
        return false;
    }
    
    /**
     * 建立请求，以表单HTML形式构造（默认）
     * @param $para 请求参数数组
     * @param $method 提交方式。两个值可选：post、get
     * @param $button_name 确认按钮显示文字
     * @return 提交表单HTML文本
     */
    function buildRequestForm($para, $method, $button_name) {
        $sHtml = "<form id='form' name='form' action='https://wappaywg.bestpay.com.cn/payWap.do' method='".$method."'>";
        while (list ($key, $val) = each ($para)) {
            $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }
    
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='".$button_name."'></form>";
    
        $sHtml = $sHtml."<script>document.forms['form'].submit();</script>";
    
        return $sHtml;
    }
    
    public function submit($param){
        
        $html_text = $this->buildRequestForm($param, 'post', '正在跳转支付页面...');
        return '<!DOCTYPE html>
				<html>
				<head>
					<meta charset="utf-8">
                    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
					<title>正在跳转支付页面...</title>
				</head>'.$html_text.'
				</body>
				</html>';
    }
    
    
}
